#!/usr/bin/env python
#-*- coding:utf-8 -*-
# and_gate.py
# Porta AND

# Copyright (c) 2007 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

from turingmachine import TuringMachine

def create_and_gate():
    tm = TuringMachine()
    states = ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'qa', 'qr']
    tm.set_states(states)
    tm.set_start_state('q1')
    tm.set_accept_state('qa')
    tm.set_reject_state('qr')
    tm.set_input_alphabet(['0', '1', '#'])
    tm.set_tape_alphabet(['x', ' '])

    # Funcao de transicao
    trans_func = {
        'q1': {'0': ('q2', 'x', TuringMachine.RIGHT),
               '1': ('q3', 'x', TuringMachine.RIGHT),
               '#': ('qa', None, TuringMachine.RIGHT)},
        'q2': {'0': ('q4', 'x', TuringMachine.RIGHT),
               '1': ('q4', 'x', TuringMachine.RIGHT)},
        'q3': {'0': ('q4', 'x', TuringMachine.RIGHT),
               '1': ('q5', 'x', TuringMachine.RIGHT)},
        'q4': {'0': ('q4', None, TuringMachine.RIGHT),
               '1': ('q4', None, TuringMachine.RIGHT),
               '#': ('q4', None, TuringMachine.RIGHT),
               ' ': ('q6', '0', TuringMachine.LEFT)},
        'q5': {'0': ('q5', None, TuringMachine.RIGHT),
               '1': ('q5', None, TuringMachine.RIGHT),
               '#': ('q5', None, TuringMachine.RIGHT),
               ' ': ('q6', '1', TuringMachine.LEFT)},
        'q6': {'0': ('q6', None, TuringMachine.LEFT),
               '1': ('q6', None, TuringMachine.LEFT),
               '#': ('q6', None, TuringMachine.LEFT),
               'x': ('q1', None, TuringMachine.RIGHT)}
    }

    tm.set_transition_function(trans_func)

    if not tm.validate_machine():
        #FIXME: jogue uma excecao adequada
        print 'maquina invalida'
        return

    return tm

def test():
    tm = create_and_gate()
    tm.debug = True

    # 1010111 AND 1100100
    # 11011000111010#
    string = '11011000111010#'
    tm.set_string(string)
    print '\nprocessando: ' + string
    tm.reset()
    accept = tm.compute()
    print '1010111 AND 1100100'
    print 'accept: ', accept

    grafo = tm.generate_graph()

    print grafo

    f = open('and_gate.dot', 'w')
    f.write(grafo)
    f.close()

if __name__ == '__main__':
    test()

